#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
//定义平方线程函数
void *thread_sqr(void *arg){
    //获取参数数值
    int num = *(int *)arg;
    //计算平方
    int *result = malloc(sizeof(int));
    *result = num * num;
    //延迟一秒钟
    sleep(1);
    //返回结果1
    pthread_exit(result);
}

int main(int argc, char const *argv[])
{
    //定义一个长度为5的数组
    int arr[5] = {1, 2, 3, 4,5};
    pthread_t threads[5];
    //获取当前时间
    struct timeval start, end;
    gettimeofday(&start, NULL);

    for(int i = 0; i < 5; i++) {
        //创建线程
        pthread_create(&threads[i], NULL, thread_sqr, &arr[i]);
    }

    //求数组平方的结果
    int results[5];
    for(int i = 0; i < 5; i++) {
        //等待线程结束并获取结果
        void *result;
        pthread_join(threads[i], &result);
        results[i] = *(int *)result;
        free(result);
    }
    gettimeofday(&end, NULL);
    //输出时间差秒
    double time_taken = (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1000000.0;
    printf("Time taken to calculate squares: %.6f seconds\n", time_taken);
    //输出平方和结果
    int sum = 0;
    for(int i = 0; i < 5; i++) {
        sum += results[i];
    }
    printf("The sum of squares is %d\n", sum);

    return 0;
}




